package com.gt.utils;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import io.jsonwebtoken.*;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @功能说明：JWT工具
 * @作者： herun
 * @创建日期：2020/2/1
 * @版本号：V1.0
 */
public class JwtUtils {
    static String AUTH_HEADER = "Authorization";
    static String SECRET = "defaultSecret";
    static Long EXPIRATION = 604800L * 1000;
    /**
     * 签发JWT
     * @param subject   可以是JSON数据 尽可能少
     * @return String
     */
    public static String createJWT(String subject) {
        Map<String, Object> claims = new HashMap<>();
        return doCreateJWT(claims, subject);
    }
    public static String createJWT(Map<String, Object> claims,String subject) {
        return doCreateJWT(claims, subject);
    }

    public static String doCreateJWT(Map<String, Object> claims, String subject) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
//        SecretKey secretKey = generalKey(SECRET);
        // 通过秘钥签名JWT
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(SECRET);
        Key secretKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
        JwtBuilder builder = Jwts.builder()
//                .setId(id)
                .setClaims(claims)
                .setSubject(subject)   // 主题
                .setIssuer("hhr")     // 签发者
                .setIssuedAt(now)      // 签发时间
                .signWith(signatureAlgorithm, secretKey); // 签名算法以及密匙
        if (EXPIRATION >= 0) {
            long expMillis = nowMillis + EXPIRATION;
            Date expDate = new Date(expMillis);
            builder.setExpiration(expDate); // 过期时间
        }
        return builder.compact();
    }


    /**
     * 验证JWT
     *
     * @param jwtStr
     * @return
     */
    public static int validateJWT(String jwtStr) {
        Claims claims = null;
        try {
            claims = parseJWT(jwtStr);
            return 0;
        } catch (ExpiredJwtException e) {
            return 1;
        } catch (SignatureException e) {
            return 2;
        } catch (Exception e) {
            return 3;
        }
    }

    /**
     * 制作秘钥
     *
     * @param secert
     * @return
     */
    public static SecretKey generalKey(String secert) {
        byte[] encodedKey = Base64.decode(secert);
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }

    /**
     * 解析JWT字符串
     *
     * @param jwt
     * @return
     * @throws Exception
     */
    public static Claims parseJWT(String jwt) {
//            SecretKey secretKey = generalKey(SECRET);
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
    // 通过秘钥签名JWT
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(SECRET);
        Key secretKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
        return Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(jwt)
                .getBody();
    }
    /**
     * <pre>
     *  验证token是否失效
     *  true:过期   false:没过期
     * </pre>
     */
    public static Boolean isTokenExpired(String token) {
        try {
            final Date expiration = getExpirationDateFromToken(token);
            return expiration.before(new Date());
        } catch (ExpiredJwtException expiredJwtException) {
            return true;
        }
    }
    /**
     * 获取jwt失效时间
     */
    public static Date getExpirationDateFromToken(String token) {
        return parseJWT(token).getExpiration();
    }


    public static String createJWT(Map<String, Object> claims,String subject, Long expiration) {
        return doCreateJWT(claims, subject, expiration);
    }

    public static String doCreateJWT(Map<String, Object> claims, String subject, Long expiration) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
//        SecretKey secretKey = generalKey(SECRET);
        // 通过秘钥签名JWT
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(SECRET);
        Key secretKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
        JwtBuilder builder = Jwts.builder()
//                .setId(id)
                .setClaims(claims)
                .setSubject(subject)   // 主题
                .setIssuer("hhr")     // 签发者
                .setIssuedAt(now)      // 签发时间
                .signWith(signatureAlgorithm, secretKey); // 签名算法以及密匙
        if (expiration >= 0) {
            long expMillis = nowMillis + expiration;
            Date expDate = new Date(expMillis);
            builder.setExpiration(expDate); // 过期时间
        }
        return builder.compact();
    }
}
